package com.idormy.sms.forwarder.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import com.google.gson.Gson
import com.idormy.sms.forwarder.R
import com.idormy.sms.forwarder.core.BaseActivity
import com.idormy.sms.forwarder.databinding.ActivitySmsCommandTestBinding
import com.idormy.sms.forwarder.server.model.SmsSendData
import com.idormy.sms.forwarder.utils.AliyunDriveUtils
import com.idormy.sms.forwarder.utils.Log
import com.idormy.sms.forwarder.utils.ScreenshotUtils
import com.idormy.sms.forwarder.utils.SmsCommandUtils
import com.idormy.sms.forwarder.utils.XToastUtils
import com.idormy.sms.forwarder.utils.ExtendedPermissions
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xutil.XUtil
import java.io.File

class SmsCommandTestActivity : BaseActivity<ActivitySmsCommandTestBinding?>(), View.OnClickListener {

    private val TAG = "SmsCommandTestActivity"
    private lateinit var aliyunDrive: AliyunDriveUtils
    private lateinit var screenCaptureLauncher: ActivityResultLauncher<Intent>
    private val prefs by lazy { XUtil.getContext().getSharedPreferences("screen_capture_prefs", android.content.Context.MODE_PRIVATE) }

    override fun viewBindingInflate(inflater: android.view.LayoutInflater?): ActivitySmsCommandTestBinding {
        return ActivitySmsCommandTestBinding.inflate(inflater!!)
    }
    
    // 移除initTitle方法，因为它在BaseActivity中不存在
    
    // 检查短信指令所需的所有权限
    private fun checkPermissions() {
        val missingPermissions = mutableListOf<String>()
        val permissionNames = mutableMapOf<String, String>()
        
        // 检查各个指令所需权限
        // 短信权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.RECEIVE_SMS)
            permissionNames[Manifest.permission.RECEIVE_SMS] = "接收短信"
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.SEND_SMS)
            permissionNames[Manifest.permission.SEND_SMS] = "发送短信"
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.READ_SMS)
            permissionNames[Manifest.permission.READ_SMS] = "读取短信"
        }
        
        // 相机权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.CAMERA)
            permissionNames[Manifest.permission.CAMERA] = "相机"
        }
        
        // 录音权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.RECORD_AUDIO)
            permissionNames[Manifest.permission.RECORD_AUDIO] = "录音"
        }
        
        // 存储权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            permissionNames[Manifest.permission.READ_EXTERNAL_STORAGE] = "读取存储"
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            permissionNames[Manifest.permission.WRITE_EXTERNAL_STORAGE] = "写入存储"
        }
        
        // 位置权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
            permissionNames[Manifest.permission.ACCESS_FINE_LOCATION] = "精确位置"
        }
        
        // 网络权限
        if (ActivityCompat.checkSelfPermission(this, ExtendedPermissions.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(ExtendedPermissions.ACCESS_WIFI_STATE)
            permissionNames[ExtendedPermissions.ACCESS_WIFI_STATE] = "访问WiFi状态"
        }
        if (ActivityCompat.checkSelfPermission(this, ExtendedPermissions.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(ExtendedPermissions.CHANGE_WIFI_STATE)
            permissionNames[ExtendedPermissions.CHANGE_WIFI_STATE] = "修改WiFi状态"
        }
        
        // 通知权限 (Android 13+)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.POST_NOTIFICATIONS)
            permissionNames[Manifest.permission.POST_NOTIFICATIONS] = "发送通知"
        }
        
        // 显示缺失的权限
        if (missingPermissions.isNotEmpty()) {
            val missingPermissionNames = missingPermissions.mapNotNull { permissionNames[it] }.joinToString(", ")
            binding?.tvStatus?.text = "警告: 以下权限未授予，相关指令可能无法使用: $missingPermissionNames"
        } else {
            binding?.tvStatus?.text = "所有短信指令所需权限已授予"
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        aliyunDrive = AliyunDriveUtils(this)
        
        // 初始化屏幕捕获权限请求器
        initScreenCaptureLauncher()
        
        // 尝试恢复之前保存的屏幕捕获权限
        restoreScreenCapturePermission()
        
        // 检查短信指令所需的所有权限
        checkPermissions()
        
        // 设置按钮点击监听
        binding?.btnFrpcStart?.setOnClickListener(this)
        binding?.btnFrpcStop?.setOnClickListener(this)
        binding?.btnHttpserverStart?.setOnClickListener(this)
        binding?.btnHttpserverStop?.setOnClickListener(this)
        binding?.btnSystemReboot?.setOnClickListener(this)
        binding?.btnSystemShutdown?.setOnClickListener(this)
        binding?.btnWifiOn?.setOnClickListener(this)
        binding?.btnWifiOff?.setOnClickListener(this)
        binding?.btnSmsSend?.setOnClickListener(this)
        binding?.btnAliyunLogin?.setOnClickListener(this)
        binding?.btnAliyunUpload?.setOnClickListener(this)
        binding?.btnCameraFront?.setOnClickListener(this)
        binding?.btnCameraBack?.setOnClickListener(this)
        binding?.btnScreenshotCapture?.setOnClickListener(this)
        binding?.btnAudioRecord?.setOnClickListener(this)
        
        updateStatus()
    }
    
    // 初始化屏幕捕获权限请求器
    private fun initScreenCaptureLauncher() {
        screenCaptureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                // 用户授权成功，初始化 MediaProjection
                try {
                    val mediaProjectionManager = getSystemService(android.media.projection.MediaProjectionManager::class.java)
                    val data = result.data
                    if (data != null) {
                        // 保存授权数据到 SharedPreferences
                        saveScreenCapturePermission(result.resultCode, data)
                        
                        // 初始化 MediaProjection
                        ScreenshotUtils.mediaProjection = mediaProjectionManager.getMediaProjection(result.resultCode, data)
                        binding?.tvStatus?.text = "屏幕捕获权限已授权"
                        XToastUtils.success("屏幕捕获权限已授权")
                        
                        // 授权成功后自动执行截图
                        executeScreenshot()
                    } else {
                        binding?.tvStatus?.text = "屏幕捕获权限授权失败：数据为空"
                        XToastUtils.error("屏幕捕获权限授权失败")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Error initializing MediaProjection: ${e.message}")
                    binding?.tvStatus?.text = "屏幕捕获权限授权失败：${e.message}"
                    XToastUtils.error("屏幕捕获权限授权失败")
                }
            } else {
                // 用户拒绝授权
                binding?.tvStatus?.text = "屏幕捕获权限被拒绝"
                XToastUtils.error("屏幕捕获权限被拒绝")
            }
        }
    }
    
    // 保存屏幕捕获权限数据
    private fun saveScreenCapturePermission(resultCode: Int, data: Intent) {
        try {
            prefs.edit().apply {
                putInt("screen_capture_result_code", resultCode)
                putString("screen_capture_data", data.toUri(Intent.URI_INTENT_SCHEME))
                apply()
            }
            Log.d(TAG, "Screen capture permission data saved")
        } catch (e: Exception) {
            Log.e(TAG, "Error saving screen capture permission: ${e.message}")
        }
    }
    
    // 恢复屏幕捕获权限
    private fun restoreScreenCapturePermission() {
        try {
            val resultCode = prefs.getInt("screen_capture_result_code", -1)
            val dataUri = prefs.getString("screen_capture_data", null)
            
            if (resultCode != -1 && dataUri != null) {
                val mediaProjectionManager = getSystemService(android.media.projection.MediaProjectionManager::class.java)
                val data = Intent.parseUri(dataUri, Intent.URI_INTENT_SCHEME)
                
                ScreenshotUtils.mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data)
                Log.d(TAG, "Screen capture permission restored successfully")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error restoring screen capture permission: ${e.message}")
            // 清除保存的无效数据
            prefs.edit().clear().apply()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_frpc_start -> testFrpc("start")
            R.id.btn_frpc_stop -> testFrpc("stop")
            R.id.btn_httpserver_start -> testHttpServer("start")
            R.id.btn_httpserver_stop -> testHttpServer("stop")
            R.id.btn_system_reboot -> testSystem("reboot")
            R.id.btn_system_shutdown -> testSystem("shutdown")
            R.id.btn_wifi_on -> testWifi("on")
            R.id.btn_wifi_off -> testWifi("off")
            R.id.btn_sms_send -> testSms()
            R.id.btn_aliyun_login -> testAliyunLogin()
            R.id.btn_aliyun_upload -> testAliyunUpload()
            R.id.btn_camera_front -> testCamera("front")
            R.id.btn_camera_back -> testCamera("back")
            R.id.btn_screenshot_capture -> testScreenshot()
            R.id.btn_audio_record -> testAudio()
        }
    }

    // Frpc指令测试
    private fun testFrpc(action: String) {
        binding?.tvStatus?.text = "正在执行: frpc#$action"
        
        val result = SmsCommandUtils.execute(this, "frpc#$action")
        if (result) {
            binding?.tvStatus?.text = "Frpc $action 指令执行成功"
            XToastUtils.success("Frpc $action 成功")
        } else {
            binding?.tvStatus?.text = "Frpc $action 指令执行失败"
            XToastUtils.error("Frpc $action 失败")
        }
    }

    // HttpServer指令测试
    private fun testHttpServer(action: String) {
        binding?.tvStatus?.text = "正在执行: httpserver#$action"
        
        val result = SmsCommandUtils.execute(this, "httpserver#$action")
        if (result) {
            binding?.tvStatus?.text = "HttpServer $action 指令执行成功"
            XToastUtils.success("HttpServer $action 成功")
        } else {
            binding?.tvStatus?.text = "HttpServer $action 指令执行失败"
            XToastUtils.error("HttpServer $action 失败")
        }
    }

    // System指令测试
    private fun testSystem(action: String) {
        binding?.tvStatus?.text = "正在执行: system#$action"
        
        val result = SmsCommandUtils.execute(this, "system#$action")
        if (result) {
            binding?.tvStatus?.text = "System $action 指令执行成功"
            XToastUtils.success("System $action 成功")
        } else {
            binding?.tvStatus?.text = "System $action 指令执行失败（需要Root权限）"
            XToastUtils.error("System $action 失败（需要Root权限）")
        }
    }

    // Wifi指令测试
    private fun testWifi(action: String) {
        binding?.tvStatus?.text = "正在执行: wifi#$action"
        
        val result = SmsCommandUtils.execute(this, "wifi#$action")
        if (result) {
            binding?.tvStatus?.text = "Wifi $action 指令执行成功"
            XToastUtils.success("Wifi $action 成功")
        } else {
            binding?.tvStatus?.text = "Wifi $action 指令执行失败"
            XToastUtils.error("Wifi $action 失败")
        }
    }

    // Sms指令测试
    private fun testSms() {
        binding?.tvStatus?.text = "正在执行: sms#send"
        
        // 创建测试短信数据
        val smsData = SmsSendData(
            simSlot = 1,
            phoneNumbers = "10086",
            msgContent = "测试短信"
        )
        
        val gson = Gson()
        val param = gson.toJson(smsData)
        
        val result = SmsCommandUtils.execute(this, "sms#send#$param")
        if (result) {
            binding?.tvStatus?.text = "Sms send 指令执行成功"
            XToastUtils.success("Sms send 成功")
        } else {
            binding?.tvStatus?.text = "Sms send 指令执行失败（需要发送短信权限）"
            XToastUtils.error("Sms send 失败（需要发送短信权限）")
        }
    }

    // Aliyun登录测试
    private fun testAliyunLogin() {
        binding?.tvStatus?.text = "正在执行: aliyun#login"
        
        val result = SmsCommandUtils.execute(this, "aliyun#login")
        if (result) {
            binding?.tvStatus?.text = "Aliyun login 指令已执行，请查看邮件"
            XToastUtils.success("Aliyun login 已执行")
        } else {
            binding?.tvStatus?.text = "Aliyun login 指令执行失败"
            XToastUtils.error("Aliyun login 失败")
        }
    }

    // Aliyun上传测试
    private fun testAliyunUpload() {
        binding?.tvStatus?.text = "正在执行: aliyun#upload"
        
        // 创建测试文件
        val testFile = File(cacheDir, "test_${System.currentTimeMillis()}.txt")
        testFile.writeText("这是一个测试文件，用于验证阿里云盘上传功能。\n创建时间: ${System.currentTimeMillis()}")
        
        val result = SmsCommandUtils.execute(this, "aliyun#upload#${testFile.absolutePath}")
        if (result) {
            binding?.tvStatus?.text = "Aliyun upload 指令已执行"
            XToastUtils.success("Aliyun upload 已执行")
        } else {
            binding?.tvStatus?.text = "Aliyun upload 指令执行失败"
            XToastUtils.error("Aliyun upload 失败")
        }
        
        // 清理测试文件
        testFile.delete()
    }

    // Camera指令测试
    private fun testCamera(action: String) {
        // 检查相机权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            binding?.tvStatus?.text = "Camera $action 失败：需要相机权限"
            XToastUtils.error("需要相机权限")
            return
        }
        
        binding?.tvStatus?.text = "正在执行: camera#$action"
        
        val result = SmsCommandUtils.execute(this, "camera#$action")
        if (result) {
            binding?.tvStatus?.text = "Camera $action 指令已执行，照片将通过邮件发送"
            XToastUtils.success("Camera $action 已执行")
        } else {
            binding?.tvStatus?.text = "Camera $action 指令执行失败"
            XToastUtils.error("Camera $action 失败")
        }
    }

    // Screenshot指令测试
    private fun testScreenshot() {
        // 检查 MediaProjection 是否已初始化
        if (ScreenshotUtils.mediaProjection == null) {
            // 如果没有权限，请求屏幕捕获权限
            requestScreenCapturePermission()
            return
        }
        
        // 如果已有权限，直接执行截图
        executeScreenshot()
    }
    
    // 请求屏幕捕获权限
    private fun requestScreenCapturePermission() {
        binding?.tvStatus?.text = "正在请求屏幕捕获权限..."
        
        try {
            val mediaProjectionManager = getSystemService(android.media.projection.MediaProjectionManager::class.java)
            val intent = mediaProjectionManager.createScreenCaptureIntent()
            screenCaptureLauncher.launch(intent)
        } catch (e: Exception) {
            Log.e(TAG, "Error requesting screen capture permission: ${e.message}")
            binding?.tvStatus?.text = "请求屏幕捕获权限失败：${e.message}"
            XToastUtils.error("请求屏幕捕获权限失败")
        }
    }
    
    // 执行截图操作
    private fun executeScreenshot() {
        // 检查 MediaProjection 是否有效
        if (ScreenshotUtils.mediaProjection == null) {
            // 如果恢复失败或 MediaProjection 已失效，重新请求权限
            binding?.tvStatus?.text = "屏幕捕获权限已失效，正在重新请求..."
            requestScreenCapturePermission()
            return
        }
        
        binding?.tvStatus?.text = "正在执行: screenshot#capture"
        
        val result = SmsCommandUtils.execute(this, "screenshot#capture")
        if (result) {
            binding?.tvStatus?.text = "Screenshot capture 指令已执行，截图将通过邮件发送"
            XToastUtils.success("Screenshot capture 已执行")
        } else {
            binding?.tvStatus?.text = "Screenshot capture 指令执行失败"
            XToastUtils.error("Screenshot capture 失败")
        }
    }

    // Audio指令测试
    private fun testAudio() {
        // 检查录音权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            binding?.tvStatus?.text = "Audio record 失败：需要录音权限"
            XToastUtils.error("需要录音权限")
            return
        }
        
        binding?.tvStatus?.text = "正在执行: audio#record"
        
        // 默认录音30秒
        val result = SmsCommandUtils.execute(this, "audio#record#30")
        if (result) {
            binding?.tvStatus?.text = "Audio record 指令已执行，录音文件将通过邮件发送"
            XToastUtils.success("Audio record 已执行")
        } else {
            binding?.tvStatus?.text = "Audio record 指令执行失败"
            XToastUtils.error("Audio record 失败")
        }
    }

    private fun updateStatus() {
        binding?.tvLoginStatus?.text = "指令测试页面已就绪"
    }
}
